package com.example.mytips.structure;

import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.event.CaretEvent;
import com.intellij.openapi.editor.event.CaretListener;
import com.intellij.openapi.editor.event.EditorFactoryEvent;
import com.intellij.openapi.editor.event.EditorFactoryListener;
import com.intellij.openapi.editor.markup.HighlighterLayer;
import com.intellij.openapi.editor.markup.HighlighterTargetArea;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.ui.JBColor;

import java.awt.Color;

/**
 * 输入光标所在行的背景颜色
 */
public class MyEditorFactoryListener implements EditorFactoryListener {

    @Override
    public void editorCreated(EditorFactoryEvent event) {
        Editor editor = event.getEditor();
        editor.getCaretModel().addCaretListener(new MyCaretListener(editor));
    }

    @Override
    public void editorReleased(EditorFactoryEvent event) {
        // Cleanup if necessary
    }

    private static class MyCaretListener implements CaretListener {
        private final Editor editor;
        private int lastLine = -1;

        public MyCaretListener(Editor editor) {
            this.editor = editor;
        }

        @Override
        public void caretPositionChanged(CaretEvent event) {
            Caret caret = event.getCaret();
            if (caret != null) {
                int currentLine = editor.getDocument().getLineNumber(caret.getOffset());
                if (currentLine != lastLine) {
                    highlightLine(currentLine);
                    lastLine = currentLine;
                }
            }
        }

        private void highlightLine(int line) {
            // 清除之前的高亮
            editor.getMarkupModel().removeAllHighlighters();

            // 设置新的高亮
            TextAttributes textAttributes = new TextAttributes();
            textAttributes.setBackgroundColor(new Color(159, 121, 238, 50)); // 设置背景颜色
            editor.getMarkupModel().addRangeHighlighter(
                    editor.getDocument().getLineStartOffset(line),
                    editor.getDocument().getLineEndOffset(line),
                    HighlighterLayer.CARET_ROW,
                    textAttributes,
                    HighlighterTargetArea.LINES_IN_RANGE
            );
        }
    }
}